<?php

namespace App\Models\video;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

// 用户登录token
class UserTokenModel extends Model
{
    protected $table = "up_user_token"; //表名
    const CREATED_AT = null;
    const UPDATED_AT = null;
    static $cacheTime = 86400 / 60;

    //获取多字段数据
    public static function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->first();
            return $data ? ($toArray ? UpTools::transferFields($data->toArray()) : UpTools::transferFields($data->toArray())) : [];
        }else{
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->get()->toArray();
            return $data ? ($toArray ? self::transferField($data) : UpTools::transferFields($data)) : [];
        }
    }

    //根据条件获取数量
    public static function getCount($filter){
        if(!empty($filter)){
            return self::query()->where($filter)->count();
        }else{
            return self::query()->count();
        }
    }

    //添加
    public static function add($data, $getId=false){
        if(!$data)
            return true;
        try {
            if ($getId) {
                $data["mall_id"] = request()->mallData["id"];
                $id = self::query()->insertGetId($data);
                return $id;
            } else {
                return self::query()->insert($data);
            }
        }catch (\Exception $e){
            return ErrorCode::code("customized", $e->getMessage());
        }
    }

    //更新
    public static function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        $res = self::query()->where($filter)->update($data);
        return $res || $res === 0 ? true : false;
    }

    //获取某字段的值
    public static function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::query()->where($filter)->value($field);
        }
        return false;
    }

    //根据删除数据
    public static function delByFilter($where){
        $result = self::query()->where($where)->delete();
        return $result;
    }

    public static function checkToken($token){
        if (!$userData = Cache::get("upWeb_" . $token)){
            $data = self::getFields("user_id", ["token" => $token, "mall_id" => request()->mallId ?: 1], true, false);
            if(empty($data['userId'])){
                return ErrorCode::code("token_expire");
            }
            $validToken = DataCacheModel::getValue("user_login_{$data["userId"]}_".UpTools::get_client_ip());
            if(!empty($validToken) && $token != $validToken){
                return ErrorCode::code("token_expire");
            }
            $userData = VideoUserModel::getFields("id,mall_id,openid,session_key,mobile,user_type", ["id" => $data["userId"]], true, false);
            Cache::put("upWeb_" . $token, $userData, self::$cacheTime); // 缓存，把登录的用户信息存起来
        }
//        if(empty($userData["mobile"]) || !preg_match('/^1[3456789]\d{9}$/', $userData["mobile"])) { // 没绑定手机号或者手机号错误
//            return ErrorCode::code("customized", "该用户没绑定手机号");
//        }
        return $userData;
    }
}